package com.example.excelutil.controller;

import com.example.excelutil.service.ExcelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Excel控制器
 */
@RestController
@RequestMapping("/api/excel")
@Slf4j
public class ExcelController {

    @Autowired
    private ExcelService excelService;

    /**
     * 根据列索引提取Excel数据
     *
     * @param file        Excel文件
     * @param columnIndex 列索引（从0开始）
     * @return 提取的数据列表
     */
    @PostMapping("/extract/index")
    public ResponseEntity<Map<String, Object>> extractByIndex(
            @RequestParam("file") MultipartFile file,
            @RequestParam("columnIndex") int columnIndex,
            @RequestParam(value = "sheetIndex", defaultValue = "0") int sheetIndex) {
        
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body(createErrorResponse("请上传Excel文件"));
        }
        
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || !(originalFilename.endsWith(".xls") || originalFilename.endsWith(".xlsx"))) {
            return ResponseEntity.badRequest().body(createErrorResponse("请上传有效的Excel文件(.xls或.xlsx)"));
        }
        
        if (columnIndex < 0) {
            return ResponseEntity.badRequest().body(createErrorResponse("列索引不能小于0"));
        }
        
        if (sheetIndex < 0) {
            return ResponseEntity.badRequest().body(createErrorResponse("工作表索引不能小于0"));
        }
        
        try {
            List<String> data = excelService.extractColumnByIndex(file, columnIndex, sheetIndex);
            return ResponseEntity.ok(createSuccessResponse(data));
        } catch (Exception e) {
            log.error("提取Excel列数据失败", e);
            return ResponseEntity.badRequest().body(createErrorResponse("提取Excel列数据失败: " + e.getMessage()));
        }
    }

    /**
     * 根据列名提取Excel数据
     *
     * @param file       Excel文件
     * @param columnName 列名
     * @return 提取的数据列表
     */
    @PostMapping("/extract/name")
    public ResponseEntity<Map<String, Object>> extractByName(
            @RequestParam("file") MultipartFile file,
            @RequestParam("columnName") String columnName,
            @RequestParam(value = "sheetIndex", defaultValue = "0") int sheetIndex) {
        
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body(createErrorResponse("请上传Excel文件"));
        }
        
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || !(originalFilename.endsWith(".xls") || originalFilename.endsWith(".xlsx"))) {
            return ResponseEntity.badRequest().body(createErrorResponse("请上传有效的Excel文件(.xls或.xlsx)"));
        }
        
        if (columnName == null || columnName.trim().isEmpty()) {
            return ResponseEntity.badRequest().body(createErrorResponse("列名不能为空"));
        }
        
        if (sheetIndex < 0) {
            return ResponseEntity.badRequest().body(createErrorResponse("工作表索引不能小于0"));
        }
        
        try {
            List<String> data = excelService.extractColumnByName(file, columnName, sheetIndex);
            return ResponseEntity.ok(createSuccessResponse(data));
        } catch (Exception e) {
            log.error("提取Excel列数据失败", e);
            return ResponseEntity.badRequest().body(createErrorResponse("提取Excel列数据失败: " + e.getMessage()));
        }
    }
    
    /**
     * 创建成功响应
     *
     * @param data 数据
     * @return 响应Map
     */
    private Map<String, Object> createSuccessResponse(List<String> data) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("data", data);
        return response;
    }
    
    /**
     * 创建错误响应
     *
     * @param message 错误信息
     * @return 响应Map
     */
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", message);
        return response;
    }
}